//
//  VPOSClientEngine.m
//  V-POS
//
//  Created by handpay on 12-10-26.
//  Copyright (c) 2012年 handpay. All rights reserved.
//

#import "ZZTongClientEngine.h"
#import "HPClientEngine.h"
#import "Utility.h"
#import "SecureManager.h"
#include "luaCommonlib.h"
#import "DefineUtil.h"
#import "ZZTongUtility.h"
#import "VPOSLocationManager.h"
#import "RFCSNValidatorController.h"
//#import "HPSwiperService.h" // mcm 

#import <HandPaySwiperModule/HandPaySwiperModule.h>
#import "RFCSNValidatorController.h"
#import "ZZTongDefine.h"

#define DEF_VERSION     @"version"

static NSString * UPDATE_URL = @"https://itunes.apple.com/cn/app/zhang-zhang-tong/id903768935?mt=8";
static ZZTongClientEngine *clientEngine = nil;
static NSString *CHANNEL = @"HXZZT";//@"00";//@"00";
//static NSString *CHANNEL = @"HPZZT";

static NSString *MOBILETYPE = @"IPHONE";//@"IPHONE"
//static NSString *MOBILETYPE = @"ANDROID";//@"ANDROID"

static NSString * HEADVERSION = @"3.5";

@interface ZZTongClientEngine ()<HPSwiperContextDelegate>{
//    int countDown;
}

@property (retain,nonatomic) NSString * unkownMsg;

@property (nonatomic, retain) NSInvocation * callback;

@property(nonatomic, retain)UIButton* getVerifyButton;
@property(nonatomic, retain)NSTimer* verifyTimer;

@end

@implementation ZZTongClientEngine
@synthesize netEngine;
@synthesize uiEngine;
@synthesize accountInfo;

+ (ZZTongClientEngine *) sharedInstance{
	if (!clientEngine) {
		clientEngine = [[ZZTongClientEngine alloc] init];
	}
	return clientEngine;
}

+ (void)releaseInstance{
    [HPClientEngine releaseInstance];
    [NSNetLib releaseInstance];
    
    if (clientEngine) {
        [clientEngine release];
        clientEngine = nil;
    }
}

- (void)dealloc{
    _callback = nil;
    self.verifyTimer = nil;
    [super dealloc];
}

- (void)swiperStateChanged:(NSNotification*)notification{
    
    if ([HPUIENG.progressView superview])
    {
        return;
    }
    NSNumber* tempState = (NSNumber*)notification.object;
    SwiperState swiperState = (SwiperState)[tempState integerValue];
    
    switch (swiperState) {
        case SwiperStateNoDeviceDected:
        {
            if(netEngine.lastReqData){
                if ([netEngine.lastReqData.action isEqualToString:NET_ACTION_ACCOUNT_TRANSFER] ||
                    [netEngine.lastReqData.action isEqualToString:NET_ACTION_SUBATM_TRANSFER] ) {
                    return;
                }
            }
            Screen* screen = [HPUIENG getCurrentScreen];
            if ([screen.screenName isEqualToString:SCR_INPUT_PASSWORD]||
                [screen.screenName isEqualToString:SCR_SWIPER] ||
                [screen.screenName isEqualToString:SCR_CONFIRM_AMOUNT] ||
                [screen.screenName isEqualToString:SCR_FAST_TRANSFER] ||
                [screen.screenName isEqualToString:SCR_CARD_OR_RECORD] ||
                [screen.screenName isEqualToString:SCR_CARD_IDENTIFY] ||
                [screen.screenName isEqualToString:SCR_SIGN_TRANSACTION] ||
                [screen.screenName isEqualToString:SCR_TRANSACTION_FAIL] ||
                [screen.screenName isEqualToString:SCR_TRANSACTION_SUCCESS]) {
                [HPUIENG popToRootScreen];
            }
            if ([screen.screenName isEqualToString:SCR_HELP]) {
                if (screen.screenData) {
                    NSString* type = [screen.screenData objectForKey:@"type"];
                    if (![NSString isNilOrEmpty:type] && [type isEqualToString:transTypeFastTransfer]) {
                        [HPUIENG popToRootScreen];
                    }
                }
            }
            [HPUIENG showAlert:@"刷卡器已拔出"];
            break;
        }
        case SwiperStateConnectFailed:
            [HPUIENG showAlert:@"刷卡器连接失败,请重新插入"];
            break;
        case SwiperStateConnected:
        {
            if ([NSString isNilOrEmpty:ZZT_CLIENG.accountInfo.account] || accountInfo.accountStatus == AccountStatusNotSubmit) {
//                [HPUIENG showAlert:@"刷卡器识别成功"];
            }else{
//                [self goCheckCSNStatus];
            }
        }
            break;
        case SwiperStateConnecting:
            [HPUIENG showWaiting:@"刷卡器连接中..."];
            break;
        case SwiperStateDectedDevice:
            break;
        default:
            break;
    }
}

- (void)clearAccountInfo{
//    if (self.accountInfo) {
//        self.accountInfo = nil;
//    }
//    AccountInfoData data = [[AccountInfoData alloc]init];
//    self.accountInfo = data;
//    [data release];
    self.accountInfo = [[[AccountInfoData alloc] init] autorelease];
}

- (id)init{
    self = [super init];
    if (self) {        
        ZZTongUIEngine* tempUIEngine = [[ZZTongUIEngine alloc] init];
        self.uiEngine = tempUIEngine;
        [tempUIEngine release];
        
        ZZTongNetEngine* tempNetEngine = [[ZZTongNetEngine alloc] init];
        tempNetEngine.verifyVerionStatus = VerifyVerionStatus_NONE;
        self.netEngine = tempNetEngine;
        [tempNetEngine release];
        
        [NOTIFICATION addObserver:self selector:@selector(swiperStateChanged:) name:SwiperStateChangeNotificationKey object:nil];
        
        [self clearAccountInfo];
        
#if ZZT_FOR_TEST
//        AccountInfoData* testAccountData = [[[AccountInfoData alloc] init] autorelease];
//        testAccountData.account = @"qabc3";
//        testAccountData.mobile = @"13812345678";
//        testAccountData.name = @"王欢欢";
//        testAccountData.certNo = @"32092219841021393X";
//        testAccountData.bankName = @"工商银行";
//        testAccountData.branchBankName = @"上海浦东第二支行";
//        testAccountData.cardNo = @"1234567890123456";
//        testAccountData.shopName = @"上海张张通奶茶店";
//        testAccountData.dayAmount = @"1234567800";
//        testAccountData.failDescpriction = @"身份证信息与身份证照片信息不符；\r\n经营场所照片不清晰；";
//        testAccountData.date = @"2014-03-11";
        
//        testAccountData.frontCCPicStatus = PhotoStatusFailed;
//        testAccountData.frontCCPicUrl = @"http://www.baidu.com/img/bdlogo.gif"; //
//        
//        testAccountData.backCCPicStatus = PhotoStatusSuccess;
//        testAccountData.backCCPicUrl = @"http://www.baidu.com/img/bdlogo.gif";
//        
//        testAccountData.holdPicStatus = PhotoStatusSuccess;
//        testAccountData.holdPicUrl  = @"http://www.baidu.com/img/bdlogo.gif";
//        
//        testAccountData.companyPicStatus = PhotoStatusSuccess;
//        testAccountData.companyPicUrl  = @"http://www.baidu.com/img/bdlogo.gif";
//        
//        testAccountData.licensePicStatus = PhotoStatusFailed;
//        testAccountData.licensePicUrl = @"http://www.baidu.com/img/bdlogo.gif";
        
        
//        self.accountInfo = testAccountData;
#else
        [self clearAccountInfo];
#endif
    }
    return self;
}

-(NSString *)getMobileType
{
    return MOBILETYPE;
}
-(NSString *)getChannel
{
    return CHANNEL;
}
-(NSString*)getAppVersion
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
- (NSString*)headServerVersion{
    return HEADVERSION;
}


- (void)gotoLoginScreen{
    [NSThread sleepForTimeInterval:1];
    [HPUIENG showScreen:SCR_LOGIN];
    [HPUIENG removeWelcomeScreen];
}

- (void)gotoLogin
{   // mcm
//    [CSNValidator clearData];
//    [ZZT_CLIENG clearAccountInfo];
//    SWIPERENG.csnStatus = CSNStatusNone;
//    [NOTIFICATION postNotificationName:WillPopToLoginNotificationKey object:nil];
//    [HPUIENG popToLoginScreen];
    
    // mcm new
    [[RFCSNValidatorController sharedInstance] clearData];
    [ZZT_CLIENG clearAccountInfo];
    [HPSwiperContext sharedInstance].avaliableService.csnStatus = CSNStatusNone;
    [NOTIFICATION postNotificationName:WillPopToLoginNotificationKey object:nil];
    [HPUIENG popToLoginScreen];
}

- (void)doExit
{
    // mcm
//    HPSwiperService* eng = [HPSwiperService sharedInstance];
//    if (eng) {
//        [eng release];
//        eng = nil;
//    }
    // mcm new
    [[HPSwiperContext sharedInstance] clearContextAndFoceStopProcess];
    [HPUIENG DoExit];
}

- (void)doUpdate{
    [HPUIENG DoBrowsUI:UPDATE_URL];
    [self doExit];
}
- (void)showQualityScreen:(NSDictionary*)resp{
    [HPUIENG showScreen:SCR_QUALITY_INDEX params:resp];
}
- (void)doSendGetBanksReq{
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_GET_BANK_LIST
                         withData:@{@"items":@(6),
                                    @"list":@[@{@"bankCode":@"1",
                                                @"bankName":@"农业银行",
                                                @"provinceFlag":@"1",
                                                @"areaFlag":@"1",
                                                @"subBankFlag":@"1"},
                                              
                                              @{@"bankCode":@"2",
                                                @"bankName":@"工商银行",
                                                @"provinceFlag":@"0",
                                                @"areaFlag":@"1",
                                                @"subBankFlag":@"1"},
                                              
                                              @{@"bankCode":@"3",
                                                @"bankName":@"交通银行",
                                                @"provinceFlag":@"0",
                                                @"areaFlag":@"0",
                                                @"subBankFlag":@"1"},
                                              
                                              @{@"bankCode":@"4",
                                                @"bankName":@"建设银行",
                                                @"provinceFlag":@"0",
                                                @"areaFlag":@"0",
                                                @"subBankFlag":@"0"},
                                              
                                              @{@"bankCode":@"5",
                                                @"bankName":@"中国银行",
                                                @"provinceFlag":@"1",
                                                @"areaFlag":@"1",
                                                @"subBankFlag":@"0"},
                                              
                                              @{@"bankCode":@"6",
                                                @"bankName":@"中国银行",
                                                @"provinceFlag":@"1",
                                                @"areaFlag":@"0",
                                                @"subBankFlag":@"0"},]}];
    //    return;
#else
    ZZTongClientEngine* zzt = ZZT_CLIENG;
    [zzt.netEngine sendRequest:NET_ACTION_GET_BANK_LIST withParams:@{KEY_CHANNEL: [zzt getChannel]} withDelegate:self];
    [zzt.uiEngine showNetWaiting];
#endif
}
- (BOOL)checkAccountStatus:(FunctionType)type{
    AccountStatus status = self.accountInfo.accountStatus;
    
    if ((status != AccountStatusSuccess) && (type != FunctionTypeCollectMoney)) {
        AlertCommandData* commandCancel = [[AlertCommandData alloc]initCommand:@"我知道了"];
        
        AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:@"资料审核通过后可使用该功能。" commands:commandCancel, nil];
        [HPUIENG showAlertWithData:alertData];
        
        [commandCancel release];
        [alertData release];
        return NO;
    }else if (status == AccountStatusNotSubmit) {

        if (type == FunctionTypeCollectMoney) {
            NSString* strTips = @"您需要提交资质审核资料后方可进行收款！";
                
            AlertCommandData* commandCancel = [[AlertCommandData alloc]initCommand:@"暂不提交"];
            AlertCommandData* commandOK = [[AlertCommandData alloc]initCommand:@"马上提交" function:@selector(submitQuality)];
            AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:strTips commands:commandOK,commandCancel, nil];
            [HPUIENG showAlertWithData:alertData];
                
            [commandCancel release];
            [commandOK release];
            [alertData release];
            return NO;
        }
    }
    return YES;
}

- (void)parseVerifyVersion:(NSDictionary *)respData{
    
    NSString* dgTrade = [respData objectForKey:KEY_TRADE];
    if (![NSString isNilOrEmpty:dgTrade]) {
        [HPCLIENTENG SaveGlobalData:dgTrade withKey:KEY_TRADE];
    }
    
    NSString* version = [respData objectForKey:DEF_VERSION];
    if (version && [version length] > 0) {
        AlertCommandData* commandCancel = [[AlertCommandData alloc] initCommand:@"取消" function:@selector(doExit)];
        AlertCommandData* commandUpdate = [[AlertCommandData alloc] initCommand:@"升级" function:@selector(doUpdate)];
        AlertData* alertData = [[AlertData alloc] initAlertData:self title:@"提示" message:[respData objectForKey:@"description"] commands:commandCancel, commandUpdate, nil];
//        alertData.leftPadding = 20;
        alertData.isMustOperate = YES;
        [HPUIENG showAlertWithData:alertData];
        
        [commandCancel release];
        [commandUpdate release];
        [alertData release];
        
        return;
    }
    [HPUIENG removeWaiting];
    if(self.netEngine.verifyVerionStatus == VerifyVerionStatus_NONE){
        [self gotoLoginScreen];
    }
    self.netEngine.verifyVerionStatus = [[respData objectForKey:NET_RESPONSE_CODE] isEqualToString:NET_RESPONSE_SUCCESS] ? VerifyVerionStatus_Success : VerifyVerionStatus_Failed;
    if (self.netEngine.verifyVerionStatus == VerifyVerionStatus_Failed) {
        NSString* errMsg = [respData objectForKey:NET_ERROR_MESSAGE];
        if (errMsg) {
            [HPUIENG showAlert:[respData objectForKey:NET_ERROR_MESSAGE]];
        }
    }
}

// mcm reason: not reference to this function
//- (void)parseBindSwiper:(NSDictionary *)respData{
//    if ([[respData objectForKey:NET_RESPONSE_CODE]isEqualToString:NET_RESPONSE_SUCCESS])
//    {
//
////        [SwiperService setCsnStatus:CSNStatusNone]; // mcm
//        [HPSwiperContext sharedInstance].avaliableService.csnStatus = CSNStatusNone; // mcm new
//            // mcm
////        [CSNValidator checkCSNStatus:^(HPSwiperResult *swiperResult) {
////            [HPUIENG showAlert:@"绑定成功"];
////        } autoTip:NO];
//        // mcm new
//        RFCSNValidatorController* ctrl = [RFCSNValidatorController sharedInstance];
//        [ctrl validateCSNComplete:^(BOOL isSucc, NSString *errInfo) {
//            [[HPUIEngine getInstance] showAlert:@"绑定成功"];
//        } autoTip:NO];
//    }
//}

- (void)parseSendCode{
    dispatch_async(dispatch_get_main_queue(), ^(){
        self.getVerifyButton.enabled = NO;
        
        [HPUIENG showAlert:@"短信验证码发送成功"];
        
//        countDown = 60;
        [self.getVerifyButton setTitle:@"60秒后重发" forState:UIControlStateDisabled];
        Screen* screen = [HPUIENG getCurrentScreen];
        if ([screen.screenName isEqualToString:SCR_VERIFY_CURRENT_MOBILE]) {
            self.verifyTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(resetButtonTitle:) userInfo:self.getVerifyButton repeats:YES];
            [self.verifyTimer fire];
        }else{
             [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(resetButtonTitle:) userInfo:self.getVerifyButton repeats:YES]fire];
        }
        self.getVerifyButton = nil;
    });
}

- (VerifyVerionStatus)getVerifyVersionStatus
{
    return self.netEngine.verifyVerionStatus;
}

- (void)resetVerifyBtnState{
    if (!self.verifyTimer || ![self.verifyTimer userInfo]) {
        return;
    }
    UIButton *button = nil;
    if ([[self.verifyTimer userInfo] isKindOfClass:[UIButton class]]) {
        button = [self.verifyTimer userInfo];
    }
    
    if (!button) {
        return;
    }
    button.enabled = YES;
    [button setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.verifyTimer invalidate];
    self.verifyTimer = nil;
    
}
- (void)showScreen:(NSDictionary*)respData{
    Screen* screen = [HPUIENG getCurrentScreen];
    
    if (screen && screen.screenName) {
        if([screen.screenName isEqualToString:SCR_REGISTER_SUCCESS]){

            [HPUIENG showIndex:0 params:@{KEY_SCR_VIEWS: @[@{KEY_SCR_ID:SCR_QUALITY_INDEX, KEY_SCR_INDEX: @(0),KEY_SCR_PARAMS:respData}]}];
        }else if([screen.screenName isEqualToString:SCR_COLLECT_MONEY]){
            NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithDictionary:respData];
            [dic setObject:SCR_COLLECT_MONEY forKey:KEY_SCREEN_NAME];
            [self showQualityScreen:dic];
        }else{
            [self showQualityScreen:respData];
        }
    }

}

- (void)responseCallBackSuccess:(NSString *)action withData:(NSDictionary *)respData{
    [HPUIENG removeWaiting];
    if ([action isEqualToString:NET_ACTION_VERIFY_VERSION]) {
        [self parseVerifyVersion:respData];
    }else if ([action isEqualToString:NET_ACTION_SEND_PHONE_CODE]) {
        [self parseSendCode];
    }else if ([action isEqualToString:NET_ACTION_GET_BANK_LIST]) {
        [HPUIENG removeWaiting];
        if ([NSThread currentThread].isMainThread) {
            [self showScreen:respData];
        }else{
            [self performSelectorOnMainThread:@selector(showScreen:) withObject:respData waitUntilDone:YES];
        }
    }
}

- (void)responseCallBackFailed:(NSString *)action withErrCode:(NSString *)errCode withErrMsg:(NSString *)msg{
    [HPUIENG removeWaiting];
    if ([action isEqualToString:NET_ACTION_VERIFY_VERSION]) {
        if (self.netEngine.verifyVerionStatus == VerifyVerionStatus_NONE) { // 初始状态下，检测失败也进主界面
            [self gotoLoginScreen];
        }else{
            [HPUIENG showAlert:msg];
        }
        self.netEngine.verifyVerionStatus = VerifyVerionStatus_Failed;
    }else if ([action isEqualToString:NET_ACTION_GET_BANK_LIST]){
        [HPUIENG showAlert:msg];
    }
}

- (void)doVerifyVersion{
    
    NSDictionary* params = @{DEF_VERSION:[self getAppVersion],
                                    @"platform":[self getMobileType],
                                    KEY_CHANNEL:VER_CHANNEL};
    LOG(@"params:%@", params);
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_VERIFY_VERSION withData:@{NET_RESPONSE_CODE:@"0"}];
#else
    [self.netEngine sendRequest:NET_ACTION_VERIFY_VERSION withParams:params withDelegate:self withAlertFlag:NO];
#endif
}

- (void)resetButtonTitle:(NSTimer*)timer{
    UIButton *button = nil;
    if ([[timer userInfo] isKindOfClass:[UIButton class]]) {
        button = [timer userInfo];
    }
    
    if (!button) {
        return;
    }

    NSString* buttonTitle = [button titleForState:UIControlStateDisabled];
  
    int countDown = [[buttonTitle substringToIndex:buttonTitle.length - 4] intValue];
    countDown--;
    if (countDown <= 0) {
        button.enabled = YES;
        [button setTitle:@"获取验证码" forState:UIControlStateNormal];
        [timer invalidate];
        self.verifyTimer = nil;
        return;
    }
    
    [button setTitle:[NSString stringWithFormat:@"%d秒后重发", countDown] forState:UIControlStateDisabled];
    if (button.enabled) {
        button.enabled = NO;
    }
}

- (void)doSendVerifyCode:(NSDictionary*)params withButton:(UIButton*)button{
    self.getVerifyButton = button;
    
#if ZZT_FOR_TEST
    [self responseCallBackSuccess:NET_ACTION_SEND_PHONE_CODE withData:nil];
#else
    [self.netEngine sendRequest:NET_ACTION_SEND_PHONE_CODE withParams:params withDelegate:self];
    [self.uiEngine showNetWaiting];
#endif
}

- (void)initApp{
    [self performSelector:@selector(doVerifyVersion) withObject:nil afterDelay:.2];
}


- (NSString*)getUrlByName:(NSString*)name{
    if ([name isEqualToString:APP_URL_NAME]) {
#if defined (ZZTSetUrl) && (ZZTSetUrl == 1)
        NSString* url = [HPCLIENTENG GetGlobalData:@"APPURL"];
        if ([NSString isNilOrEmpty:url]) {
            return APPSERVERURL;
        }else{
            return url;
        }
#else
        return APPSERVERURL;
#endif
        return APPSERVERURL;
    }else if ([name isEqualToString:CUP_URL_NAME]) {
        return CUPSERVERURL;
    }
    return APPSERVERURL;
}

- (void)doAsyncFunction:(id)target func:(SEL)func arg:(NSObject*)obj{
    NSThread* thread = [[NSThread alloc] initWithTarget:target selector:func object:obj];
    [thread start];
    [thread release];
}

    //mcm
//- (void)submitQuality
//{
//        [SWIPERENG selectSwiperAndGetCsn:^(HPSwiperResult *swiperResult) {
//            [CSNValidator validateCSNAndExcuteBlock:^(HPSwiperResult *result) {
//                if ([result.message isEqualToString:LocationErrMsg])
//                {
//                    return;
//                }
//                if ([result.message isEqualToString:LocationErrMsg2])
//                {
//                    [HPUIENG showAlert:result.message];
//                    return;
//                }
//                if (result.isSuccess || SwiperService.csnStatus == CSNStatusUnbound)
//                {
//                    Screen* screen = [HPUIENG getCurrentScreen];
//                   if ([screen.screenName isEqualToString:SCR_REGISTER_SUCCESS]) {
//                       screen.canSave = NO;
//                    }
//                    [ZZT_CLIENG doSendGetBanksReq];
//                }
//                else
//                {
//                    [HPUIENG showAlert:result.message];
//                }
//            } autoTip:NO];
//        } isShow:NO];
//}

-(void)submitQuality
{
    HPSwiperContext* ctx = [HPSwiperContext sharedInstance];
    if (ctx.connectedDeviceCSN.length)
        [self swiperCsnDidChange:ctx.connectedDeviceCSN];
    else
    {
        [ctx addDelegate:self];
        [HPUIENG showScreen:SCR_SWIPER_SELECT];
    }
    
}

#pragma mark -

-(void)choiseYourDevice:(NSArray*)devices{}

-(void)swiperCsnDidChange:(NSString*)didChangeCsn
{
    RFCSNValidatorController* validator = [RFCSNValidatorController sharedInstance];
    [validator validateCSNComplete:^(BOOL succ, NSString *errInfo)
    {
        [[HPSwiperContext sharedInstance] removeDelegate:self];
        if(errInfo)
            [HPUIENG showAlert:errInfo];
        else if(didChangeCsn.length)
        {
            Screen* screen = [HPUIENG getCurrentScreen];
            if ([screen.screenName isEqualToString:SCR_REGISTER_SUCCESS])
                screen.canSave = NO;
            [ZZT_CLIENG doSendGetBanksReq];
        }
    } autoTip:NO];
}

@end
